<template>
  <div class="mail-container">
    <template v-for="(item, index) in list" :key="index">
      <listItem @click="checkedClick(item, index)" :data="item" @deleteItem="deleteItem" @lookDetail="lookDetail">
      </listItem>
    </template>
    <pagination v-if="list.length" @selectAll="selectAll" :dataSource="list" @changePage="changePage" :isSelect="true"
      :total="total" :scroll="scroll" :isShowPagination="true" :selfChecked="isSelectAll" :isClose="true"
      :showCheckDelete="true">
      <template #opration>
        <a-button :style="{ 'margin-left': '24px' }" @click="readAll"
          :disabled="isDisable || !btnPerm.includes('markAsReadAble')">标记为已读</a-button>
        <a-button :style="{ 'margin-left': '8px' }" @click="deleteSelectedAll"
          :disabled="isDisable || !btnPerm.includes('deleteAble')">删除</a-button>
      </template>
    </pagination>
    <div class="empty-box">
      <img src="../../assets/imgs/empty.png" alt="">
      <div class="empty-text">
        暂无消息
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, nextTick, computed, onMounted, createVNode } from "vue";
import { Modal, message } from "ant-design-vue";
import listItem from "./item.vue";
import { useRouter } from "vue-router";
import msgModal from "@/components/modal/modelConfig/MsGModal";
import pagination from "@/components/pagination/index.vue";
import { dataSourceType } from "@/type.d";
import request from "@/api/index";
import { routerPerm } from "@/utils/common";

//data
const btnPerm = ref<any[]>([]);
const list = ref<dataSourceType[]>([]);
let scroll: dataSourceType = reactive({ y: "", isFixed: true });
let rowSelection = ref<(string | number)[]>([]);
const isSelectAll = ref<boolean>(false); // 是否需要配分页器
let isDisable = ref<boolean>(true); // 是否需要配分页器
const selectedRow = ref<dataSourceType[]>([]);
let datas = reactive<dataSourceType>({});
const total = ref<number | string>(0);

const router = useRouter();
//method
// 全选
const selectAll = (selected: [], selectedRows: [], changeRows: []) => {
  isSelectAll.value = !isSelectAll.value;
  list.value.forEach((item: any) => {
    item.checked = isSelectAll.value;
  });
};

//单击
const checkedClick = (item: any, index: number) => {
  list.value[index].checked = !item.checked;
  sysMessageRead(item);
  nextTick(() => {
    isSelectAll.value = list.value.every((item: any) => item.checked == true);
  });
};
// 获取分页的改变
// 切换分页器
const changePage = (data: { pageCurrent: any; pageSize: any }) => {
  datas = {
    pageNumber: data.pageCurrent,
    pageSize: data.pageSize,
  };
  fetchSysMessageUnReadPage();
};

const deleteSelectedAll = async () => {
  //删除已选所有内容类型
  let keys: (string | number)[] = rowSelection.value;
  Modal.confirm(
    Object.assign({}, msgModal.confirm, {
      title: `是否确定删除选中信息？删除后无法恢复`,
      content: "",
      icon: createVNode("i", {
        class: "iconfont icon-warn warning_ICON",
      }),
      okText: "确定",
      onOk: async () => {
        deleteItem(keys);
        Modal.destroyAll();
        isSelectAll.value = false;
      },
      onCancel() {
        Modal.destroyAll();
      },
    })
  );
};

//删除单个
const deleteItem = async (ids: any) => {
  await request.fetchSysMessageDelete({ ids }).then((res: any) => {
    if (res.code == "00000 00000") {
      message.success(res.message);
      fetchSysMessageUnReadPage();
    } else {
      message.error(res.message);
    }
  });
};
// 消息已读
const sysMessageRead = (item: any) => {
  let ids = [item.id];
  request.sysMessageRead({ ids }).then((res: any) => { });
};
//查看详情
const lookDetail = (data: dataSourceType) => {
  if (data.msgType === 1 || data.msgType === 4) {
    router.push({
      path: "/workplace/index",
    });
  } else if (data.msgType === 3) {
    router.push({
      path: "/content/newContent",
      query: {
        contentId: data.param?.contentId,
        channelId: data.param?.channelId,
        id: data.param?.modelId,
        modelName: data.param?.modelName,
      },
    });
  } else if (data.msgType === 6) {
    router.push({
      path: "/member/auditedMember",
      query: {
        userName: data.param?.userName,
      },
    });
  } else if (data.msgType === 7) {
    router.push({
      path: "/system/threeMember/auditMember",
      query: {
        logId: data.param?.logId,
      },
    });
  }
};

//查看全部
const readAll = async () => {
  let ids: (string | number)[] = rowSelection.value;
  request
    .fetchSysMessageRead({ ids })
    .then((res: any) => {
      if (res.code == "00000 00000") {
        fetchSysMessageUnReadPage();
        rowSelection.value = [];
        message.success(res.message);
        isSelectAll.value = false;
      } else {
        message.error(res.message);
      }
    })
    .catch((err: any) => {
      throw new Error(err);
    });
};

//获取未读分页
const fetchSysMessageUnReadPage = async () => {
  const postData = {
    pageNumber: datas.pageNumber || 1,
    pageSize: datas.pageSize || 10,
  };
  const data = await request.fetchSysMessageUnReadPage(postData);
  total.value = data.total;
  list.value = data.records;
  list.value.length &&
    list.value.forEach((item: any) => {
      item.checked = false;
    });
};

//computed
isDisable = computed(() => {
  return !list.value.find((item: any) => item.checked == true);
});

rowSelection = computed(() => {
  let ids: any = [];
  list.value.map((item: any) => {
    if (item.checked) {
      ids.push(item.id);
    }
  });
  return ids;
});

onMounted(() => {
  btnPerm.value = routerPerm();
  fetchSysMessageUnReadPage();
});
</script>

<style lang="less" scoped>
.mail-container {
  height: calc(100% - 126px);
  overflow-y: scroll;
  .empty-box {
    width: 100%;
    height: 100vh;
    display: flex;
    flex-direction: column;
    flex-wrap: wrap;
    justify-content: center;
    align-items: center;
    .empty-text {
      transform: translateX(-7px);
      margin-top: 16px;
      font-size: 14px;
      color: #262626;
    }
  }
}
</style>
